package com.example.sharedelementdemo

import android.app.SharedElementCallback
import android.content.Intent
import android.graphics.Matrix
import android.graphics.RectF
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity(), MyAdapter.CallBack {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: MyAdapter
    private val mipmaps = ArrayList<LocalBean>()

    private lateinit var layoutManager: GridLayoutManager
    private var bundle: Bundle? = null

    private var exitTag = ""

    companion object {
        var exitLiveData = MutableLiveData<String>()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.rv)

        initRv()

        exitLiveData.observeForever {
            exitTag = it

            /**
            View viewAtPosition = layoutManager.findViewByPosition(MainActivity.currentPosition);
            if (viewAtPosition == null || layoutManager
            .isViewPartiallyVisible(viewAtPosition, false, true)) {
            recyclerView.post(() -> layoutManager.scrollToPosition(MainActivity.currentPosition));
            }
             */
            recyclerView.scrollToPosition(exitTag.toInt())
        }
    }

    private fun initRv() {
        adapter = MyAdapter(this)
        mipmaps.add(LocalBean(R.mipmap.wangze1, "0"))
        mipmaps.add(LocalBean(R.mipmap.other1, "1"))
        mipmaps.add(LocalBean(R.mipmap.other2, "2"))
        mipmaps.add(LocalBean(R.mipmap.wangze2, "3"))
        mipmaps.add(LocalBean(R.mipmap.other3, "4"))
        mipmaps.add(LocalBean(R.mipmap.other4, "5"))
        mipmaps.add(LocalBean(R.mipmap.other5, "6"))
        mipmaps.add(LocalBean(R.mipmap.wangze3, "7"))
        mipmaps.add(LocalBean(R.mipmap.wangze4, "8"))
        mipmaps.add(LocalBean(R.mipmap.wangze5, "9"))
        mipmaps.add(LocalBean(R.mipmap.wangze6, "10"))
        mipmaps.add(LocalBean(R.mipmap.wangze7, "11"))
        mipmaps.add(LocalBean(R.mipmap.wangze8, "12"))
        mipmaps.add(LocalBean(R.mipmap.wangze9, "13"))
        mipmaps.add(LocalBean(R.mipmap.wangze10, "14"))
        layoutManager = recyclerView.layoutManager as GridLayoutManager
        recyclerView.adapter = adapter

        adapter.submitList(mipmaps)

        setExitSharedElementCallback(object : SharedElementCallback() {
            override fun onCaptureSharedElementSnapshot(
                sharedElement: View?,
                viewToGlobalMatrix: Matrix?,
                screenBounds: RectF?
            ): Parcelable {
//                sharedElement?.setAlpha(1f);
                return super.onCaptureSharedElementSnapshot(
                    sharedElement,
                    viewToGlobalMatrix,
                    screenBounds
                )
            }

            override fun onMapSharedElements(
                names: MutableList<String>?,
                sharedElements: MutableMap<String, View>?
            ) {
                super.onMapSharedElements(names, sharedElements)
                Log.d("ActivityOptionsCompat", "ExitSharedElementCallback111")
                if (bundle != null) {
                    val i: Int = bundle!!.getInt("index", 0)
//                    Log.d("setExitSharedElementCallback", "onMapSharedElements  $i")
                    sharedElements!!.clear()
                    names!!.clear()
                    val itemView = recyclerView.findViewHolderForAdapterPosition(i)
//                    val itemView: View? = layoutManager.findViewByPosition(i)
                    val imageView = itemView?.itemView?.findViewById<ImageView>(R.id.item_image)
                    //注意这里第二个参数，如果放置的是条目的item则动画不自然。放置对应的imageView则完美
                    imageView?.let {
                        sharedElements[mipmaps[i].tag] = imageView
                    }
//                    Log.d("setExitSharedElementCallback", "onMapSharedElements  " + mipmaps[i].tag)
                    bundle = null
                }

                if (exitTag.isNotEmpty()) {
                    sharedElements!!.clear()
                    names!!.clear()
                    val itemView: View? = layoutManager.findViewByPosition(exitTag.toInt())
                    val imageView = itemView?.findViewById<ImageView>(R.id.item_image)
                    //注意这里第二个参数，如果放置的是条目的item则动画不自然。放置对应的imageView则完美

                    imageView?.let {
                        sharedElements[exitTag] = imageView
                    }
                    exitTag = ""
                }
            }
        })
    }

    override fun select(position: Int, imageView: ImageView) {
        val intent = Intent(this, MainActivity2::class.java)
        intent.putExtra("position", position)

        val options: ActivityOptionsCompat = ActivityOptionsCompat
            .makeSceneTransitionAnimation(
                this,
                imageView,
                mipmaps[position].tag
            ) // mAdapter.get(position).getUrl()
//            Log.d("setExitSharedElementCallback", "onClick" + mipmaps[position].tag)
//            Log.d("ActivityOptionsCompat", "onClick" + mipmaps[position].tag)
        startActivity(intent, options.toBundle())
    }
}